<?php
namespace Admin\Controller;
use Think\Controller;
class BaseController extends Controller {

    public function __construct()
    {
        parent::__construct();
        $uid = session('userid');
        if ($uid){
            $this->redirect('/Admin/index/index');
        }
    }

    public function login()
    {
        $this->display();
    }

    public function logindo()
    {
        $username       =   I('post.username','','htmlspecialchars');
        $password       =   I('post.password','','htmlspecialchars');
        $null_password  =   md5('');

        if (! $username) 
        {
            $msg['state']  =   -1;
            $msg['error']  =   '请输入账号';
            $this->ajaxReturn($msg);
        }

        if (! $password || $null_password == $password) 
        {
            $msg['state']  =   -1;
            $msg['error']  =   '请输入密码';
            $this->ajaxReturn($msg);
        }

        $password   =   md5($password);
        //安全限制
        //self::limit();

        self::check($username,$password);
    }

    private function check($username,$password)
    {
        //登陆验证
        $where['username']  =   $username;
        $admin_data         =   M('admin')->where($where)->find();
        if (empty($admin_data)) 
        {
            $msg['state']  =   -1;
            $msg['error']  =   '账号不存在';
            $this->ajaxReturn($msg);
        }

        if ($admin_data['password'] != $password) 
        {
            $msg['state']  =   -1;
            $msg['error']  =   '密码不正确';
            $this->ajaxReturn($msg);
        }

        self::save_cache($admin_data);
        $msg['state']  =   200;
        $msg['error']  =   '登录成功    ';
        $this->ajaxReturn($msg);
    }

    private function save_cache($admin_data)
    {
        session('userid',$admin_data['userid']);
        session('username',$admin_data['username']);
        session('roleid',$admin_data['roleid']);
    }

    public function add()
    {
        $data['username']   =   'admin';
        $data['password']   =   md5(md5('yuanyi2018'));
        $data['roleid']     =   1;

        M('admin')->add($data);

    }


    public function logout()
    {
        session(null); // 清空当前的session
        $this->redirect('/Admin/Base/login', '', 3, '页面跳转中...');
    }

}   